package com.freesid.ask.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/login")
public class LoginController {

	private static Log log = LogFactory.getLog(LoginController.class);
	
	/**
	 * 失败几次后显示验证码
	 */
	public static int showCaptchaFailureTime = 1 ; 
	
	/**
	 * 失败次数常量
	 */
	public static String F_NUMBER = "fnumber";

	/**
	 * 失败次数
	 * 
	 * @param request
	 * @return
	 */
	protected int failureNumber(HttpServletRequest request) {
		Integer failure = (Integer) request.getSession().getAttribute(F_NUMBER);
		return failure == null ? 0 : failure ;
	}
	
	protected void resetFailureNumber(HttpServletRequest request) {
		request.getSession().removeAttribute(F_NUMBER);
	}
	
	protected void plusFailureNumber(HttpServletRequest request) {
		Integer failure = (Integer) request.getSession().getAttribute(F_NUMBER);
		int num = failure == null ? 0 : failure;
		num++;
		request.getSession().setAttribute(F_NUMBER, num) ;
	}

	/**
	 * 登录页面
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String login(HttpServletRequest request, HttpServletResponse response) {
		String logout = request.getParameter("logout"); 
		if(logout != null&&logout.equalsIgnoreCase("true")) {
			Subject subject = SecurityUtils.getSubject();
			SecurityUtils.getSecurityManager().logout(subject);
		}
		int fnum = failureNumber(request);
		if (fnum >= showCaptchaFailureTime) {
			request.setAttribute("showCode", true);
		}
		return "login";
	}

	
	
	
	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView loginPost(HttpServletRequest request, HttpServletResponse response) {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String code = request.getParameter("code");
		int fnum = failureNumber(request);
		if(fnum >= showCaptchaFailureTime){
			boolean val = validateCaptcha(request, code);
			if(!val) {
				plusFailureNumber(request);
				return new ModelAndView("redirect:/login");
			}
		}
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username,password);
		try {
			subject.login(token);
		}catch (AuthenticationException e) {
			log.debug("Error authenticating.", e);
			plusFailureNumber(request);
			return new ModelAndView("redirect:/login");
        }
		
		
		return new ModelAndView("redirect:/Ask.html?gwt.codesvr=127.0.0.1:9997");
	}

	protected boolean validateCaptcha(HttpServletRequest request, String capt){
		String captchaId = (String) request.getSession().getAttribute(CodeImageController.SESSION_KEY_VALUE);
		if(captchaId == null) {
			return false ;
		}
		request.getSession().removeAttribute(CodeImageController.SESSION_KEY_VALUE);
		if (log.isDebugEnabled()) {
			log.debug("Validating captcha response: '" + captchaId + "'");
		}
		if (StringUtils.equalsIgnoreCase(captchaId, capt)) {
			return true;
		}
		return false;
	}
}
